package com.seeyon.ctp.rest.resources;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.seeyon.ctp.api.annotation.ApiOperation;
import com.seeyon.ctp.portal.po.PortalSpaceFix;
import com.seeyon.ctp.portal.space.manager.SpaceManager;
import com.seeyon.ctp.portal.util.SpaceFixUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.portal.mobile.manager.MobilePortalManager;
import com.seeyon.ctp.portal.portlet.manager.ShortCutManager;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.json.JSONUtil;

@Path("shortcut")
@Produces({ MediaType.APPLICATION_JSON })
public class ShortCutResource extends BaseResource {
    private static final Log log = LogFactory.getLog(ShortCutResource.class);
    private ShortCutManager  shortCutManager;
    private MobilePortalManager          mobilePortalManager;
    private SpaceManager spaceManager;
    public SpaceManager getSpaceManager(){
        if (spaceManager == null) {
            spaceManager = (SpaceManager) AppContext.getBean("spaceManager");
        }
        return spaceManager;
    }

    public ShortCutManager getShortCutManager() {
        if (shortCutManager == null) {
            shortCutManager = (ShortCutManager) AppContext.getBean("shortCutManager");
        }
        return shortCutManager;
    }
    
    public MobilePortalManager getMobilePortalManager() {
        if (mobilePortalManager == null) {
            mobilePortalManager = (MobilePortalManager) AppContext.getBean("mobilePortalManager");
        }
        return mobilePortalManager;
    }
    
    /**
     * 获取移动端应用磁贴数据
     * @param sourceValue 移动端应用磁贴数据 newaffair|commonPortlet|0,meetingCreatePortlet|commonPortlet|1,newCreateTask|commonPortlet|2,meetingPendingPortlet|meetingPortlet|3,vreportMPortlet|commonPortlet|4,formquery|commonPortlet|5,hrSign|AttendancePortlet|6
     * @return 
     * <pre>
     * {
     * "0":[{"groupId":"1","groupName":"分组名称01","groupType":0,"sort":0,"portletJsons":["",""]},{"groupId":"1","groupName":"分组名称01","groupType":0,"sort":0,"portletJsons":["",""]}],
     * "1":[{"groupId":"1","groupName":"分组名称02","groupType":0,"sort":0,"portletJsons":["",""]},{"groupId":"1","groupName":"分组名称01","groupType":0,"sort":0,"portletJsons":["",""]}],
     * "2":[{"groupId":"1","groupName":"分组名称03","groupType":0,"sort":0,"portletJsons":["",""]},{"groupId":"1","groupName":"分组名称01","groupType":0,"sort":0,"portletJsons":["",""]}]
     * }
     * </pre>
     * @throws BusinessException
     */
    @GET
    @Path("portlets/{sourceValue}")
    @ApiOperation(name = "获取移动端应用磁贴数据", scenes = "M3：获取移动端应用磁贴数据")
    public Response getShortCutByEntityId(@PathParam("sourceValue") String sourceValue) throws BusinessException {
        return ok(getShortCutManager().getMobileShortCut(sourceValue));
    }
    @GET
    @Path("portlets")
    @ApiOperation(name = "获取个人移动端待添加磁贴", scenes = "M3：获取个人移动端待添加磁贴")
    public Response getShortCutDataByEntityId(@QueryParam("sourceValue") String sourceValue) throws BusinessException{
        return ok(getShortCutManager().getMobileShortCut(sourceValue));
    }
    /**
     * 
     * @param params
     * <pre>
	 * 
     *    params.spaceId: String 必填 空间ID
     *    params.entityId: String 必填 人员ID
     *    params.sourceValue: String 必填 应用磁贴数据  newaffair|commonPortlet|0,meetingCreatePortlet|commonPortlet|1,newCreateTask|commonPortlet|2,meetingPendingPortlet|meetingPortlet|3,vreportMPortlet|commonPortlet|4,formquery|commonPortlet|5,hrSign|AttendancePortlet|6
     *    
	 * </pre> 
     * @return
     * @throws BusinessException
     */
    @POST
    @Path("saveShortCut")
    @Consumes({ MediaType.APPLICATION_JSON })
    @ApiOperation(name = "保存·磁贴配置页面", scenes = "M3：保存·磁贴配置页面")
    public Response saveShortCut(Map<String, Object> params) throws BusinessException {
        Long spaceId = ParamUtil.getLong(params, "spaceId");
        Long entityId = ParamUtil.getLong(params, "entityId");
        String sourceValue = ParamUtil.getString(params, "sourceValue");
        boolean sectionAllowdefined = false;
        if(spaceId!=null){
            PortalSpaceFix spaceFix = this.getSpaceManager().getSpaceFix(spaceId);
            if(spaceFix!=null){
                SpaceFixUtil util=new SpaceFixUtil(spaceFix.getExtAttributes());
                boolean allowdefined = util.isAllowdefined();
                if(!allowdefined){
                    sectionAllowdefined=true;//空间不允许自定义
                }
            }
        }
        List<Map<String, Object>> shortcutJson = (List<Map<String, Object>>) params.get("groupList");
        Map<String, Object> property = new HashMap<String, Object>();
        if (Strings.isNotBlank(sourceValue) && sourceValue.indexOf("|") == -1) {
            String pro = getShortCutManager().getShortCutPropertyById(sourceValue);
            if(Strings.isNotBlank(pro)){
                property = (Map<String, Object>)JSONUtil.parseJSONString(pro);
            }
        }
        String result = "";
        String shortCutId = getShortCutManager().saveShortCutConfig(sourceValue, "m3mobile", shortcutJson, property);
        if(Strings.isBlank(shortCutId)){
            return success(result, "failure to save magnetic paste data.", 500);
            //return success(result, "磁贴数据保存失败", 500);
        }
        try{
            if(!sectionAllowdefined){
                result = getMobilePortalManager().updataMobileShortCut(spaceId, entityId, shortCutId);
            }
           else {
               getShortCutManager().saveShortcut4SectionAllowed(entityId,0L,Long.valueOf(shortCutId));
                result = spaceId + ";" + entityId + ";" + shortCutId;
            }
        }catch(BusinessException e){
            log.debug("", e);
        	return success(result, "failure of updating spatial data by magnetic paste.", 500);
            //return success(result, "磁贴更新空间数据失败", 500);
        }
        return success(result, "", 200);
    }
    
    /**
     * 
     * @param params
     * params.portletKeys:  MyTask|timeManagement|PortletCategory,trackPortlet|collaboration|PortletCategory
     * @return
     * @throws BusinessException
     */
    @POST
    @Path("tipNumber")
    @Consumes({ MediaType.APPLICATION_JSON })
    @ApiOperation(name = "获取多条磁贴角标数", scenes = "M3：获取多条磁贴角标数")
    public Response getPortletTipNumber(Map<String, Object> params) throws BusinessException {
        String portletKeys = ParamUtil.getString(params, "portletKeys");
        String entityId=ParamUtil.getString(params,"entityId");
        Long entityIdNum=0L;
        if(Strings.isNotBlank(entityId)&&Strings.isDigits(entityId)){
            entityIdNum=Long.valueOf(entityId);
        }
        if(Strings.isBlank(portletKeys)){
        	return success("", "failure to acquire the number of magnetic stickers.", 500);
            //return success("", "磁贴数获取失败", 500);
        }
        String dataJson = getShortCutManager().getPortletTipNumber(portletKeys, entityIdNum);
        return success(dataJson, "", 200);
    }

}
